import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/Login'
import Main from "@/views/Main";
import Dept from "@/views/sys/Dept";
import User from "@/views/sys/User";
import Role from "@/views/sys/Role";
import Menu from "@/views/sys/Menu";
import Post from "@/views/sys/Post";
import Course from "@/views/tb/Course";
import Activity from "@/views/tb/Activity";
import axios from "axios";
import store from "@/store/index"
import NotFound from "@/views/404";

Vue.use(VueRouter)

// 基础路由
const constantRoutes = [
    {
        path: "/",
        redirect: "/login"  // 重定向到登录页
    },
    {
        path: "/login",
        name: "Login",
        component: Login,
    },
    {
        path: "/main",
        name: "Main",
        component: Main,
    }
]

// 防止连续点击多次路由报错
let routerPush = VueRouter.prototype.push;
let routerReplace = VueRouter.prototype.replace;
// push
VueRouter.prototype.push = function push(location) {
    return routerPush.call(this, location).catch(err => err)
}
// replace
VueRouter.prototype.replace = function replace(location) {
    return routerReplace.call(this, location).catch(err => err)
}

// 创建路由实例
const router = new VueRouter({
    routes: constantRoutes
})

// 重置路由的核心方法 用新的matcher替换旧的matcher
export function resetRouter() {
    // 创建一个全新的路由实例(仅含常量路由)
    const newRouter = new VueRouter({
        routes: constantRoutes
    })
    // 关键操作:替换matcher 彻底清除动态路由
    router.matcher = newRouter.matcher
}



// 全局路由守卫
router.beforeEach(async (to, from, next) => {
    // 显示页面标题
    document.title = to.meta.title ? `${to.meta.title} - 后台管理系统` : '后台管理系统'

    // 判断是否登录
    const token = store.state.token
    if (to.path === "/login" || to.path === "/") {
        next()
        return
    }

    if (!token) {
        Vue.prototype.$message.error("无权访问，请先登录")
        next("/login")
        return
    }

    // 如果已经登录但用户信息为空，则获取用户信息
    if (store.state.userInfo.username === '未登录' || router.getRoutes().length < 5) {
        try {
            const res = await axios.get("/api/getInfo")
            if (res.data.code === 200) {
                // 保存用户信息
                store.commit("setUserInfo", {
                    username: res.data.username,
                    "avatar": res.data.avatar == null ? store.state.userInfo.avatar : res.data.avatar,
                    permissions: res.data.permissions
                })

                // 保存动态菜单
                store.commit("setMenus", res.data.menus)
                console.log("tets",res.data.menus)
                // 添加动态路由
                const dynamicRoutes = formatRouters(res.data.menus)
                dynamicRoutes.forEach(route => {
                    router.addRoute('Main',route)
                })
                // 最后添加404路由，确保在所有路由之后
                router.addRoute({path: "*", name: "NotFound", component: NotFound});
                // 确保路由已添加完成，再进行导航
                next({...to, replace: true})
            } else {
                Vue.prototype.$message.error(res.data.msg)
                next("/login")
            }
        } catch (error) {
            console.error("获取用户信息失败:", error)
            if (error.response) {
                // 请求已发出，服务器响应状态码不在 2xx 范围内
                console.error("错误状态码:", error.response.status)
                console.error("错误数据:", error.response.data)
            } else if (error.request) {
                // 请求已发出，但没有收到响应
                console.error("无响应错误:", error.request)
            } else {
                // 发送请求时出错
                console.error("请求配置错误:", error.message)
            }
            Vue.prototype.$message.error("获取用户信息失败，请重新登录")
            next("/login")
        }

    } else {
        next()
    }
})
// 格式化路由数据
const formatRouters = (menus) => {
    let myRouters = [];
    menus.forEach((menu) => {
        let myRouter = {
            path: menu.path  || '/not',
            name: menu.menuName,
            meta: {
                title: menu.menuName,
                icon: menu.icon || ''
            }
        }

        if (menu.component) {
            // 使用import方式引入组件，避免require在生产环境的问题
            myRouter.component = () => import('@/views/' + menu.component + '.vue')
        }else {
            myRouter.component = () => import('@/views/404.vue')
        }

        if (menu.children && menu.children.length > 0) {
            myRouter.children = formatRouters(menu.children)
        }

        myRouters.push(myRouter);
    })
    return myRouters;
}
export default router
